package com.dongdongshop.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.dongdongshop.domain.AjaxResult;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.CartService;
import com.dongdongshop.util.CookieUtils;
import com.dongdongshop.vo.CartVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("cart")
public class CarController {

    @DubboReference(timeout = 500000000)
    private CartService cartService;

    //获取购物车
    @RequestMapping("getCart")
    @ResponseBody
    public AjaxResult<List<CartVo>> getCart(HttpServletRequest request,HttpServletResponse response){

        // 如果未登录将购物车数据暂时存放在 cookie中
        // 如果已登录就从 cookie 中取出来,和 redis 中的数据合并
        // 合并完成之后 将合并的数据存放到redis中 然后在将cookie中的购物车数据清除


        //从 shiro 登录方法获取用户信息
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();

        //获取cookie
        String cartList = CookieUtils.getCookieValue(request, "cartList", true);
        //判断cookie是否为空
        if (StrUtil.isBlank(cartList)) {
            cartList = "[]";
        }
        List<CartVo> cartVoCookie = JSONUtil.toList(cartList, CartVo.class);
        //判断用户是否登录
        if (user == null) { // 未登录, 从cookie中获取未登录之前购物车的信息
            return AjaxResult.OK().setData(cartVoCookie);
        }else { //已登录, 从redis 中获取购物车信息

            List<CartVo> cartVoRedis = cartService.getCartListFromRedis(user.getId());

            //判断 如果cookie中有购物车信息的话就去合并,
            if (cartVoCookie.size() > 0 && cartVoRedis != null) {
                // 将 cookie 中的数据和redis中的数据进行合并
                List<CartVo> margeList = cartService.mergeCartList(cartVoCookie,cartVoRedis);
                // 将合并过后的数据放入到redis中
                cartService.addCartToRedis(user.getId(),margeList);
                // 并且删除 cookie
                CookieUtils.deleteCookie(request,response,"cartList");

                return AjaxResult.OK().setData(margeList);
            }
            //cookie 中没有购物车信息的话 直接 return redis中的购物车信息
            return AjaxResult.OK().setData(cartVoRedis);
        }
    }


    //增加购物车
    @RequestMapping("addCart")
    public String addCart(HttpServletRequest request,HttpServletResponse response,Long skuId, Integer num){

        addCarts(request,response,skuId,num);

        return "success-cart";
    }

    //增加购物车
    @RequestMapping("addCartAjax")
    @ResponseBody
    public AjaxResult<List<CartVo>> addCartAjax(HttpServletRequest request,HttpServletResponse response,Long skuId, Integer num){

        addCarts(request,response,skuId,num);

        return getCart(request,response);
    }


    private void addCarts(HttpServletRequest request,HttpServletResponse response,Long skuId, Integer num){
        //调用写好的getCart方法
        AjaxResult<List<CartVo>> r = getCart(request,response);
        List<CartVo> cartVoList = r.getData();

        //调用购物车服务,添加购物车数据
        cartVoList = cartService.addCart(cartVoList,skuId,num);

        //从 shiro 登录方法获取用户信息
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();

        if (user == null) { // 未登录, 将购物车信息写到 cookie中

            //将我们添加的购物车数据写入到cookie中
            CookieUtils.setCookie(request, response, "cartList", JSONUtil.toJsonStr(cartVoList), true);
        }else { // 已登录 ,将购物车信息写到 Redis中
            cartService.addCartToRedis(user.getId(),cartVoList);
        }
    }


    //判断结算时 用户有无登录
    @RequestMapping("getOrderInfo")
    @ResponseBody
    public AjaxResult getOrderInfo(){
        //从 shiro 登录方法获取用户信息
        try {
            TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
            return AjaxResult.OK().setData(user);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.ERROR();
        }
    }


    //操作cookie
    @RequestMapping("addCookie")
    @ResponseBody
    public String addCookie(HttpServletRequest request, HttpServletResponse response){
        CookieUtils.setCookie(request,response,"username","zhangsan",true);
        return "ok";
    }

    //操作cookie
    @RequestMapping("getCookie")
    @ResponseBody
    public String getCookie(HttpServletRequest request){
        CookieUtils.getCookieValue(request,"username",true);
        return "ok";
    }

    //操作cookie
    @RequestMapping("delCookie")
    @ResponseBody
    public String delCookie(HttpServletRequest request,HttpServletResponse response){
        CookieUtils.deleteCookie(request,response,"username");
        return "ok";
    }

}
